package com.changzhu.community.service;

import com.changzhu.community.dao.LoginTicketMapper;
import com.changzhu.community.dao.UserMapper;
import com.changzhu.community.entity.LoginTicket;
import com.changzhu.community.entity.User;
import com.changzhu.community.util.CommunityConstant;
import com.changzhu.community.util.CommunityUtil;
import com.changzhu.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author leiliu
 * @date 22-6-24 上午11:56
 */
@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    //根据id查询
    public User findUserById(int userId){
        return userMapper.selectById(userId);
    }

    public Map<String,Object> register(User user){
        Map<String,Object > map=new HashMap<>();

        //参数校验
        if(user==null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空");
            return map;
        }

        //用户验证
        User u=userMapper.selectByName(user.getUsername());
        if(u!=null){
            map.put("usernameMsg","该账号已存在！");
            return map;
        }
        u=userMapper.selectByEmail(user.getEmail());
        if(u!=null) {
            map.put("emailMsg","该邮箱已被注册");
            return map;
        }

        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword())+user.getSalt());
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        //设置随机头像
        user.setHeaderUrl(String.format(
                "http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)
        ));
        user.setCreateTime(new Date());
        //插入数据库
        userMapper.insertUser(user);

        //激活
        Context context=new Context();
        context.setVariable("email",user.getEmail());
        //http://localhost:8080/community/activation/101/code //自定义激活url
        String url=
                domain
                +contextPath
                +"/activation/"
                +user.getId()
                +"/"
                +user.getActivationCode();
        context.setVariable("url",url);
        String content=templateEngine.process("/mail/activation",context);
        mailClient.sendMessage(user.getEmail(),"激活账号",content);
        return map;
    }


    /**
     * 激活功能
     * 需要清理缓存
     * @param userId
     * @param code
     * @return
     */
    public int activation(int userId,String code){
        User user=userMapper.selectById(userId);
        if(user.getStatus()==1){
            //1 代表已经激活
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            //更改激活状态
            userMapper.updateStatus(userId,1);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILED;
        }
    }


    public Map<String,Object> login(String username,String password,int expiredSeconds){
        Map<String,Object> map=new HashMap<>();

        //空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }

        //验证账号
        User user=userMapper.selectByName(username);
        if(user==null){
            map.put("usernameMsg","该账号不存在！");
            return map;
        }

        //验证状态
        if(user.getStatus()==0){
            map.put("usernameMsg","该账号未激活！");
            return map;
        }

        //验证密码
        password=CommunityUtil.md5(password)+user.getSalt();
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确！");
            return map;
        }

        //若上面的验证都通过,生成登陆凭证
        LoginTicket loginTicket=new LoginTicket();
        //设置用户id
        loginTicket.setUserId(user.getId());
        //设置凭证码为随机字符串
        loginTicket.setTicket(CommunityUtil.generateUUID());
        //设置凭证有效状态
        loginTicket.setStatus(0);
        //设置过期时间
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds*1000));
        //存入登陆凭证
        loginTicketMapper.insertLoginTicket(loginTicket);
        //浏览器只需要保存ticket,通过它可以查询到登陆凭证即可
        map.put("ticket",loginTicket.getTicket());
        return map;
    }
}
